<template>
  <div class="position">
    <!-- 定位 -->
    <div class="position-header">
      <p>
        <i class="iconfont icon-zuo" @click="Return"></i>
      </p>
      <p>选择城市</p>
      <p></p>
    </div>
    <div class="position-nav">
      <baidu-map @ready="handler"></baidu-map>
      <div>{{address}}</div>
    </div>
    <van-index-bar :index-list="cityList">
      <div v-for="(item,ind) in TwoCityList" :key="ind">
        <van-index-anchor :index="item.keys"></van-index-anchor>
        <van-cell v-for="(val, i) in item.citys" :key="i" :title="val.name" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { getCityList } from "@/api/index.js";
import { cPinyin } from "@/utils/index.js";
export default {
  name: "position",
  data() {
    return {
      //   address: "定位中...",
      cityList: [], //城市数据,
      TwoCityList: [] //需要遍历的城市数组
    };
  },
  created() {
    this.getCity();
  },
  computed: {
    ...mapState(["address"])
  },
  methods: {
    //获取所有城市
    ...mapMutations(["ACTIVE"]),
    getCity() {
      getCityList().then(res => {
        console.log(res);
        let cityList = res.data.data.map(item => {
          //截取--slice
          return {
            ...item,
            //拼音转字母
            ct: cPinyin(item.name.slice(0, 1))
          };
        });
        console.log(cityList);
        //去重---new set
        let newArr = Array.from(new Set(cityList.map(item => item.ct)));
        console.log(newArr);
        //  排序---sort A,B,C,D....
        this.cityList = newArr.sort((a, b) => {
          return a.charCodeAt(0) - b.charCodeAt(0);
        });
        this.TwoCityList = this.cityList.map(item => {
          // 过滤--filter
          return {
            keys: item,
            citys: cityList.filter(val => val.ct === item)
          };
        });
      });
    },
    handler({ BMap }) {
      var geolocation = new BMap.Geolocation();
      const that = this;
      geolocation.getCurrentPosition(function(city) {
        that.ACTIVE(city.address.city);
        console.log(city.address.city);
        // console.log(this.ACTIVE)
      });
    },
    Return() {
      this.$router.push("/main");
    }
  }
};
</script>
<style scoped>
.position {
  width: 100%;
  height: 100%;
}
.position-header {
  width: 100%;
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
}
</style>